package com.ziq.zcamp.dialog

import android.graphics.Rect
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.*
import android.widget.Toast
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import com.ziq.base.base.BaseDialog
import com.ziq.base.extension.*
import com.ziq.zcamp.R
import com.ziq.zcamp.bean.post.CommentItem
import com.ziq.zcamp.bean.post.ReplyCommentItem
import com.ziq.zcamp.databinding.DialogCommentInputBinding
import com.ziq.zcamp.manager.GlobalContextManager
import com.ziq.zcamp.post.CommentViewModel
import com.ziq.zcamp.util.KeyboardHelper

class CommentInputDialog(val activity: AppCompatActivity, val post_id: String, val post_uid: Int, val position:Int? = 0, var commentItem: CommentItem? = null, var replyCommentItem: ReplyCommentItem? = null, val source:String = "" ) : BaseDialog(activity),
    ViewTreeObserver.OnGlobalLayoutListener {

    private val binding: DialogCommentInputBinding by binding()
    val mViewModel: CommentViewModel by activity.viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window?.decorView?.let {
            window?.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
            window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE or WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE)
            window?.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
            window!!.decorView.viewTreeObserver.addOnGlobalLayoutListener(this)
        }

        binding.root.fitsSystemWindows = true // 会使得root 键盘弹出的时候增加 paddingbottom
        binding.etCommentActionInput.requestFocus()
        binding.root.click {
            dismiss()
        }

        if(commentItem !=null){
            binding.etCommentActionInput.setHint("回复 @${commentItem?.user_info?.nick_name} :")
            mViewModel.currentInput.postValue("")
        }else if(replyCommentItem !=null){
            binding.etCommentActionInput.setHint("回复 @${replyCommentItem?.reply_info?.nick_name} :")
            mViewModel.currentInput.postValue("")
        }else {
            if(mViewModel.currentInput.value?.isNotEmpty() == true){
                binding.etCommentActionInput.setText(mViewModel.currentInput.value)
                binding.etCommentActionInput.setSelection(mViewModel.currentInput.value!!.length)
            }


            binding.etCommentActionInput.addTextChangedListener(object : TextWatcher {
                override fun afterTextChanged(s: Editable?) {
                    mViewModel.currentInput.postValue(binding.etCommentActionInput.text.toString())
                }

                override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
                }

                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                }
            })
        }

        binding.btnSend.click {
            val content = binding.etCommentActionInput.text.toString()
            if(content.isEmpty()){
                return@click
            }
            if(post_id.isNotEmpty() && post_uid != 0){
                if(commentItem != null){
                    mViewModel.replyComment(
                        post_id,
                        post_uid,
                        content,
                        position,
                        commentItem,
                        null,
                    )
                } else if(replyCommentItem != null){
                    mViewModel.replyComment(
                        post_id,
                        post_uid,
                        content,
                        position,
                        null,
                        replyCommentItem,
                    )
                } else {
                    mViewModel.sendComment(
                        post_id,
                        post_uid,
                        content
                    )
                }
                mViewModel.currentInput.postValue("")
                dismiss()
            } else {
                val errMsg = GlobalContextManager.getString(R.string.data_error)
                Toast.makeText(activity, errMsg, Toast.LENGTH_SHORT).show()
            }
        }
    }

    override fun initWidth(): Int {
        return ViewGroup.LayoutParams.MATCH_PARENT
    }

    override fun initHeight(): Int {
        return ViewGroup.LayoutParams.MATCH_PARENT
    }

    override fun initGravity(): Int {
        return Gravity.BOTTOM or Gravity.CENTER
    }

    override fun dismiss() {
        window?.decorView?.let {
            window!!.decorView.viewTreeObserver.removeOnGlobalLayoutListener(this)
        }
        KeyboardHelper.hideSoftInputForce(GlobalContextManager.getCurrentActivity(), binding.root.windowToken)
        super.dismiss()
    }

    var rootViewVisibleHeight = 0
    override fun onGlobalLayout() {
        //获取当前根视图在屏幕上显示的大小
        val r =  Rect();
        window!!.decorView.getWindowVisibleDisplayFrame(r);

        val visibleHeight = r.height();
        if (rootViewVisibleHeight == 0) {
            rootViewVisibleHeight = visibleHeight;
            return
        }

        if (rootViewVisibleHeight == visibleHeight) {
            return;
        }

        //根视图显示高度变小超过200，可以看作软键盘显示了
        if (rootViewVisibleHeight - visibleHeight > 200) {
            rootViewVisibleHeight = visibleHeight;
            return
        }

        //根视图显示高度变大超过200，可以看作软键盘隐藏了
        if (visibleHeight - rootViewVisibleHeight > 200) {
            rootViewVisibleHeight = visibleHeight
            dismiss()
            return
        }

    }


}